import { ref } from 'vue'
import { getToken } from '@/utils/auth'

export function useWebSocket() {
  const ws = ref(null)
  const baseUrl = import.meta.env.VITE_WS_API // 从环境变量获取 WebSocket 地址

  const connect = (path) => {
    const token = getToken()
    const url = `${baseUrl}${path}?token=${token}`
    
    try {
      ws.value = new WebSocket(url)
      
      ws.value.onopen = () => {
        console.log('WebSocket 连接成功')
      }
      
      ws.value.onerror = (error) => {
        console.error('WebSocket 连接错误:', error)
      }
      
      ws.value.onclose = () => {
        console.log('WebSocket 连接关闭')
      }
    } catch (error) {
      console.error('创建 WebSocket 连接失败:', error)
    }
  }

  const disconnect = () => {
    if (ws.value && ws.value.readyState === WebSocket.OPEN) {
      ws.value.close()
      ws.value = null
    }
  }

  return {
    ws,
    connect,
    disconnect
  }
} 